package com.atguigu.gmall.all.controller;

import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.product.feign.ProductFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.ServletContextAware;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.List;
import java.util.Map;

/**
 * 首页
 */
@Controller
public class IndexController {

    //远程调用
    @Autowired
    private ProductFeignClient productFeignClient;
    //进入首页
    @GetMapping
    public String index(){
        return "index";
    }
/*    @GetMapping("/")
    public String index(Model model){

        List<Map> categoryList = productFeignClient.getCategoryList();
        model.addAttribute("list",categoryList);
        return "index/index";
    }*/

    @Autowired
    private TemplateEngine templateEngine;//引入坐标 spring-boot-starter-thymeleaf

    //生成静态化页面  首页  定时器触发 执行静态化生成
    @GetMapping("/createHtml")
    @ResponseBody
    public Result createHtml(HttpSession httpSession) throws Exception{
//        1、查询数据
        List<Map> categoryList = productFeignClient.getCategoryList();
//        2、生成静态化页面（Thymeleaf 模板引擎 ）
        Context context = new Context();
        context.setVariable("list",categoryList);
//        3 输出指定的位置
/*        String path = ClassUtils.getDefaultClassLoader()
                .getResource("classpath:templates").getPath();*/
        ClassPathResource classPathResource = new ClassPathResource("templates/");
        String path = classPathResource.getClassLoader().getResource("templates/").getPath();
        //httpSession.getServletContext().getRealPath("classpath:templates/")
//        Writer writer = new OutputStreamWriter
//                (new FileOutputStream(path + "index.html"),"utf-8");
        Writer writer = new PrintWriter(new File(path + "index.html"),"utf-8");
                //参数1：模板 位置
        //参数2：数据
        //参数3:输出流 字符
        templateEngine.process("index/index",context,writer);


        return Result.ok();
    }

}
